/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package systole.persistence.brokersDB;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import systole.domain.clinicalInformation.Medicine;
import systole.exceptions.ExceptionDAO;
import systole.persistence.FacadeDB;
import systole.persistence.brokersInterface.MedicineSyncBroker;
import systole.synchronization.remote.entities.MedicineRemote;

/**
 *
 * @author Juan Manuel
 */
public class MedicineSyncBrokerDB extends BrokerDB implements MedicineSyncBroker {

    public void saveMedicineRemote(MedicineRemote medicineRemote) throws ExceptionDAO {
        try {
            this.logger.logDebug("saving remote medicine");
            Session currentSession = FacadeDB.getInstance().getCurrentSession();
            currentSession.save(medicineRemote);
            this.logger.logDebug("remote medicine saved");
        } catch (HibernateException e) {
            this.logger.logError("error on save medicine remote, msg: " + e.getMessage());
            throw new ExceptionDAO("No se pudieron guardar los cambios", e.fillInStackTrace());
        }
    }

    public List<MedicineRemote> getMedicinesToUpdate() throws ExceptionDAO {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public List<Medicine> getMedicinesToUpload() throws ExceptionDAO {
        try {
            this.logger.logDebug("getting medicines to upload");
            Session currentSession = FacadeDB.getInstance().getCurrentSession();
            String hql = "select m from MedicineRemote mr right join mr.medicine m where mr=null";
            Query query = currentSession.createQuery(hql);
            @SuppressWarnings("unchecked")
            List<Medicine> list = query.list();
            this.logger.logDebug("get successfully");
            return list;
        } catch (HibernateException e) {
            this.logger.logError("error on get medicines to upload, msg: " + e.getMessage());
            throw new ExceptionDAO("No se pudieron obtener los medicamentos", e.fillInStackTrace());
        }
    }

    public Medicine getMedicineByRemoteId(int remoteId) throws ExceptionDAO {
        try {
            this.logger.logDebug("getting medicine by remote id");
            Session currentSession = FacadeDB.getInstance().getCurrentSession();
            Criteria criteria = currentSession.createCriteria(
                    MedicineRemote.class).add(Restrictions.eq("remoteId", remoteId)).setMaxResults(1);
            MedicineRemote medicineRemote = (MedicineRemote) criteria.uniqueResult();
            this.logger.logDebug("get successfully");
            return (medicineRemote != null ? medicineRemote.getMedicine() : null);
        } catch (HibernateException e) {
            this.logger.logError("error on get medicine by remote id, msg: " + e.getMessage());
            throw new ExceptionDAO("No se pudieron obtener los medicamentos", e.fillInStackTrace());
        }
    }

    public MedicineRemote getMedicineRemoteByMedicine(Medicine medicine) throws ExceptionDAO {
        try {
            this.logger.logDebug("getting medicine remote by local medicine");
            Session currentSession = FacadeDB.getInstance().getCurrentSession();
            Criteria criteria = currentSession.createCriteria(
                    MedicineRemote.class).add(Restrictions.eq("medicine", medicine)).setMaxResults(1);
            MedicineRemote medicineRemote = (MedicineRemote) criteria.uniqueResult();
            this.logger.logDebug("get successfully");
            return medicineRemote;
        } catch (HibernateException e) {
            this.logger.logError("error on get remote medicine by medicine, msg: " + e.getMessage());
            throw new ExceptionDAO("No se pudieron obtener los medicamentos", e.fillInStackTrace());
        }
    }

    public int getLastRemoteMedicineIdSynchronized() throws ExceptionDAO {
        try {
            this.logger.logDebug("getting last remote medicine sync");
            Session currentSession = FacadeDB.getInstance().getCurrentSession();
            Criteria criteria = currentSession.createCriteria(
                    MedicineRemote.class).addOrder(Order.desc("remoteId")).setMaxResults(1);
            MedicineRemote medicineRemote = (MedicineRemote) criteria.uniqueResult();
            this.logger.logDebug("get successfully");
            return (medicineRemote != null ? medicineRemote.getRemoteId() : -1);
        } catch (HibernateException e) {
            this.logger.logError("error on get last remote medicine synchronized, msg: " + e.getMessage());
            throw new ExceptionDAO("No se pudieron obtener los medicamentos", e.fillInStackTrace());
        }
    }
}
